<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '打卡成功',
    navigationBarBackgroundColor: '#f8f8f8',
    navigationBarTextStyle: 'black'
  },
}
</route>

<script setup lang="ts">
import type { PunchRecordRespVO } from '@/api/types/punch'
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getPunchDetail } from '@/api/punch'
import ShareCanvas from '@/components/ShareCanvas.vue'

// 页面数据
const punchDetail = ref<PunchRecordRespVO | null>(null)
const loading = ref(false)
const isGeneratingShare = ref(false)
const punchId = ref<number | null>(null)
const shareImageUrl = ref<string>('')
const isSharedView = ref(false) // 是否为分享查看模式
const shareCanvasRef = ref<any>(null)

// 计算属性
const totalReadingTime = computed(() => {
  // 使用真实的阅读时长数据（秒转分钟）
  const readingTimeInSeconds = punchDetail.value?.readingTime || 0
  return Math.round(readingTimeInSeconds / 60)
})

// 格式化日期
function formatDate(dateStr?: string) {
  if (!dateStr)
    return ''
  const date = new Date(dateStr)
  const today = new Date()

  if (date.toDateString() === today.toDateString()) {
    return '今天'
  }

  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 格式化阅读时长
function formatReadingTime(minutes: number) {
  if (minutes < 60) {
    return `${minutes}分钟`
  }
  const hours = Math.floor(minutes / 60)
  const remainingMinutes = minutes % 60
  return remainingMinutes > 0 ? `${hours}小时${remainingMinutes}分钟` : `${hours}小时`
}

// 图片加载错误处理
function onImageError(event: any) {
  console.log('图片加载失败:', event)
  // 可以设置默认图片
}

// 加载打卡详情
async function loadPunchDetail(id: number) {
  try {
    loading.value = true
    console.log('加载打卡详情，ID:', id)

    const response = await getPunchDetail(id)
    if (response.code === 0 && response.data) {
      punchDetail.value = response.data
      console.log('打卡详情加载成功:', punchDetail.value)
    }
    else {
      throw new Error(response.msg || '获取打卡详情失败')
    }
  }
  catch (error) {
    console.error('获取打卡详情失败:', error)
    uni.showToast({
      title: '获取打卡详情失败',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 分享打卡
async function shareCheckin() {
  if (isGeneratingShare.value || !punchDetail.value)
    return

  try {
    isGeneratingShare.value = true

    // 检查是否为公开打卡
    if (!punchDetail.value.isPublic) {
      uni.showModal({
        title: '提示',
        content: '当前打卡记录为私有，是否设为公开后分享？',
        success: (res) => {
          if (res.confirm) {
            // 这里可以调用API更新打卡记录为公开
            performShare()
          }
        },
      })
      return
    }

    performShare()
  }
  catch (error) {
    console.error('分享失败:', error)
    uni.showToast({
      title: '分享失败，请重试',
      icon: 'none',
    })
  }
  finally {
    isGeneratingShare.value = false
  }
}

// 执行分享操作
async function performShare() {
  try {
    // 生成分享卡片
    if (!shareImageUrl.value && punchDetail.value && shareCanvasRef.value) {
      uni.showLoading({ title: '生成分享卡片中...' })
      await shareCanvasRef.value.generateShareCard()
    }
    else {
      // 直接分享
      uni.showToast({
        title: '请点击右上角分享',
        icon: 'none',
        duration: 2000,
      })
    }
  }
  catch (error) {
    uni.hideLoading()
    console.error('分享失败:', error)
    uni.showToast({
      title: '分享失败，请重试',
      icon: 'none',
    })
  }
}

// 分享卡片生成成功回调
function onShareCardGenerated(imageUrl: string) {
  uni.hideLoading()
  shareImageUrl.value = imageUrl

  uni.showToast({
    title: '请点击右上角分享',
    icon: 'none',
    duration: 2000,
  })

  console.log('分享卡片生成成功:', imageUrl)
}

// 分享卡片生成失败回调
function onShareCardError(error: any) {
  uni.hideLoading()
  console.error('生成分享卡片失败:', error)
  uni.showToast({
    title: '生成分享卡片失败',
    icon: 'none',
  })
}

// 返回首页
function goBack() {
  uni.switchTab({
    url: '/pages/index/index',
  })
}

// 跳转到应用（分享查看模式）
function goToApp() {
  uni.switchTab({
    url: '/pages/index/index',
  })
}

// 重新加载
async function retryLoad() {
  if (punchId.value) {
    await loadPunchDetail(punchId.value)
  }
}

// 微信分享配置
onShareAppMessage(() => {
  const bookCount = punchDetail.value?.bookCount || 0
  return {
    title: `我今天读了${bookCount}本绘本，一起来阅读吧！`,
    path: `/pages/checkin-result/index?punchId=${punchId.value}&shared=true`,
    imageUrl: shareImageUrl.value || '', // 使用生成的分享卡片图片
  }
})

// 页面加载
onLoad(async (options: any) => {
  console.log('打卡展示页面参数:', options)

  // 检查是否为分享查看模式
  if (options.shared === 'true') {
    isSharedView.value = true
  }

  if (options.punchId) {
    punchId.value = Number.parseInt(options.punchId)
    await loadPunchDetail(punchId.value)

    // 如果是分享查看模式，需要验证打卡记录是否公开
    if (isSharedView.value && punchDetail.value && !punchDetail.value.isPublic) {
      uni.showModal({
        title: '提示',
        content: '该打卡记录为私有，无法查看',
        showCancel: false,
        success: () => {
          uni.switchTab({
            url: '/pages/index/index',
          })
        },
      })
    }
  }
  else {
    uni.showToast({
      title: '参数错误',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 2000)
  }
})
</script>

<template>
  <view class="checkin-result-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner" />
      <text class="loading-text">
        加载中...
      </text>
    </view>

    <!-- 主要内容 -->
    <view v-else-if="punchDetail" class="main-content">
      <!-- 成功提示区域 -->
      <view class="success-banner">
        <view class="success-icon">
          <text class="icon-text">
            🎉
          </text>
        </view>
        <text class="success-title">
          打卡成功！
        </text>
        <text class="success-subtitle">
          今天的阅读收获已记录
        </text>
      </view>

      <!-- 阅读成果展示 -->
      <view class="reading-summary">
        <view class="summary-header">
          <text class="header-title">
            今日阅读成果
          </text>
          <text class="reading-date">
            {{ formatDate(punchDetail?.punchDate) }}
          </text>
        </view>

        <view class="stats-grid">
          <view class="stat-item">
            <text class="stat-number">
              {{ punchDetail?.bookCount || 0 }}
            </text>
            <text class="stat-label">
              本绘本
            </text>
          </view>
          <view class="stat-item">
            <text class="stat-number">
              {{ formatReadingTime(totalReadingTime) }}
            </text>
            <text class="stat-label">
              阅读时长
            </text>
          </view>
          <view class="stat-item">
            <text class="stat-number">
              {{ punchDetail?.dayCount || 1 }}
            </text>
            <text class="stat-label">
              连续打卡
            </text>
          </view>
        </view>
      </view>

      <!-- 绘本展示区域 -->
      <view v-if="punchDetail?.books && punchDetail.books.length > 0" class="books-section">
        <view class="section-header">
          <text class="section-title">
            今日阅读的绘本
          </text>
        </view>

        <view class="books-grid">
          <view
            v-for="book in punchDetail.books"
            :key="book.id"
            class="book-item"
          >
            <view v-if="!book.cover" class="book-cover-placeholder">
              <uni-icons type="paperplane" size="40" color="#ddd" />
            </view>
            <image
              v-else
              class="book-cover"
              :src="book.cover"
              mode="aspectFit"
              @error="onImageError"
            />
            <text class="book-title">
              {{ book.title }}
            </text>
            <text v-if="book.bookSetTitle" class="book-set">
              {{ book.bookSetTitle }}
            </text>
          </view>
        </view>
      </view>

      <!-- 打卡心得展示 -->
      <view v-if="punchDetail?.commentText" class="comment-section">
        <view class="section-header">
          <text class="section-title">
            阅读心得
          </text>
        </view>

        <view class="comment-content">
          <text class="comment-text">
            {{ punchDetail.commentText }}
          </text>
        </view>
      </view>

      <!-- 分享按钮区域 -->
      <view class="share-section">
        <!-- 只有非分享查看模式才显示分享按钮 -->
        <button
          v-if="!isSharedView"
          class="share-btn"
          :class="{ loading: isGeneratingShare }"
          :disabled="isGeneratingShare"
          @click="shareCheckin"
        >
          <text class="share-icon">
            📤
          </text>
          <text class="btn-text">
            {{ isGeneratingShare ? '生成分享卡片中...' : '分享打卡' }}
          </text>
        </button>

        <!-- 分享查看模式显示不同的按钮 -->
        <button v-if="isSharedView" class="explore-btn" @click="goToApp">
          <text class="btn-text">
            我也要开始阅读
          </text>
        </button>

        <button class="back-btn" @click="goBack">
          <text class="btn-text">
            {{ isSharedView ? '返回首页' : '返回首页' }}
          </text>
        </button>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-container">
      <view class="error-icon">
        😕
      </view>
      <text class="error-title">
        加载失败
      </text>
      <text class="error-subtitle">
        请检查网络连接后重试
      </text>
      <button class="retry-btn" @click="retryLoad">
        <text class="btn-text">
          重新加载
        </text>
      </button>
    </view>

    <!-- 分享Canvas组件 -->
    <ShareCanvas
      ref="shareCanvasRef"
      :visible="false"
      :punch-data="punchDetail"
      :user-info="{ nickname: '小读者' }"
      @generated="onShareCardGenerated"
      @error="onShareCardError"
    />
  </view>
</template>

<style lang="scss" scoped>
// 导入公共样式变量
@import '@/styles/variables.scss';

.checkin-result-container {
  background: $bg-gradient;
  min-height: 100%;
  padding: $container-padding;
  padding-top: 10px;
  padding-bottom: 40px;
  // margin-top: -20px;
}

/* 加载状态 */
.loading-container {
  @include center-flex;
  flex-direction: column;
  height: 60vh;
  gap: $spacing-lg;

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid $border-color-light;
    border-top: 3px solid $primary-blue;
    border-radius: $border-radius-full;
    animation: spin 1s linear infinite;
  }

  .loading-text {
    font-size: $font-size-base;
    color: $medium-gray;
    font-family: $font-family;
  }
}

/* 错误状态 */
.error-container {
  @include center-flex;
  flex-direction: column;
  height: 60vh;
  gap: $spacing-lg;
  padding: $spacing-2xl;

  .error-icon {
    font-size: 48px;
    margin-bottom: $spacing-md;
  }

  .error-title {
    font-size: $font-size-xl;
    font-weight: $font-weight-bold;
    color: $dark-gray;
    font-family: $font-family;
    margin-bottom: $spacing-sm;
  }

  .error-subtitle {
    font-size: $font-size-base;
    color: $medium-gray;
    font-family: $font-family;
    text-align: center;
    margin-bottom: $spacing-2xl;
  }

  .retry-btn {
    padding: $spacing-md $spacing-2xl;
    background: $primary-blue;
    border-radius: $border-radius-3xl;
    border: none;
    @include center-flex;
    transition: $transition-all;
    box-shadow: $shadow-blue;

    &:active {
      transform: scale(0.95);
      box-shadow: $shadow-blue-lg;
    }

    .btn-text {
      font-size: $font-size-base;
      font-weight: $font-weight-medium;
      color: $white;
      font-family: $font-family;
    }
  }
}

/* 成功提示区域 */
.success-banner {
  padding: $spacing-3xl $spacing-2xl;
  margin: $spacing-md;
  margin-top: 0px;
  text-align: center;
  border-radius: $border-radius-xl;
  @include glass-effect(0.3);
  backdrop-filter: blur(24px);
  border: 2px solid $white-80;
  box-shadow: $shadow-blue-lg;
  position: relative;
  // top: 10px;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 150px;
    height: 150px;
    border-radius: $border-radius-full;
    background: $green-gradient;
    opacity: 0.3;
    filter: blur(30px);
    z-index: 1;
    animation: success-pulse 3s infinite ease-in-out;
    transform: translate(-50%, -50%);
  }

  .success-icon,
  .success-title,
  .success-subtitle {
    position: relative;
    z-index: 2;
  }

  .success-icon {
    margin-bottom: $spacing-lg;

    .icon-text {
      font-size: 48px;
      display: block;
      animation: bounce 2s infinite;
    }
  }

  .success-title {
    display: block;
    font-size: $font-size-2xl;
    font-weight: $font-weight-bold;
    color: $dark-gray;
    font-family: $font-family;
    margin-bottom: $spacing-sm;
    text-shadow: 0 2px 4px rgba(255, 255, 255, 0.5);
  }

  .success-subtitle {
    display: block;
    font-size: $font-size-base;
    color: rgba(51, 51, 51, 0.7);
    font-weight: $font-weight-regular;
    font-family: $font-family;
  }
}

/* 阅读成果展示 */
.reading-summary {
  margin: $spacing-md;
  padding: $spacing-2xl;
  border-radius: $border-radius-xl;
  @include glass-effect;
  border: 2px solid $border-color-light;
  box-shadow: $shadow-lg;

  .summary-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-2xl;

    .header-title {
      font-size: $font-size-lg;
      font-weight: $font-weight-bold;
      color: $dark-gray;
      font-family: $font-family;
    }

    .reading-date {
      font-size: $font-size-sm;
      color: $medium-gray;
      font-family: $font-family;
    }
  }

  .stats-grid {
    display: flex;
    justify-content: space-around;
    gap: $spacing-md;

    .stat-item {
      text-align: center;
      flex: 1;

      .stat-number {
        display: block;
        font-size: $font-size-3xl;
        font-weight: $font-weight-bold;
        color: $primary-blue;
        font-family: $font-family;
        margin-bottom: $spacing-xs;
      }

      .stat-label {
        display: block;
        font-size: $font-size-sm;
        color: $medium-gray;
        font-family: $font-family;
      }
    }
  }
}

/* 通用区域样式 */
.section-header {
  margin-bottom: $spacing-lg;

  .section-title {
    font-size: $font-size-lg;
    font-weight: $font-weight-bold;
    color: $dark-gray;
    font-family: $font-family;
  }
}

/* 绘本展示区域 */
.books-section {
  margin: $spacing-md;
  padding: $spacing-2xl;
  border-radius: $border-radius-xl;
  @include glass-effect;
  border: 2px solid $border-color-light;
  box-shadow: $shadow-lg;

  .books-grid {
    display: flex;
    flex-wrap: wrap;
    gap: $spacing-lg;
    justify-content: flex-start;

    .book-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: calc(33.333% - #{$spacing-lg});
      min-width: 80px;

      .book-cover {
        width: 60px;
        height: 80px;
        border-radius: $border-radius-md;
        box-shadow: $shadow-lg;
        margin-bottom: $spacing-sm;
        background-color: $white-10;
      }

      .book-cover-placeholder {
        width: 60px;
        height: 80px;
        border-radius: $border-radius-md;
        background-color: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: $spacing-sm;
        border: 1px solid #eee;
      }

      .book-title {
        font-size: $font-size-sm;
        color: $dark-gray;
        text-align: center;
        line-height: $line-height-tight;
        font-family: $font-family;
        font-weight: $font-weight-medium;
        margin-bottom: $spacing-xs;
        @include text-ellipsis-multiline(2);
      }

      .book-set {
        font-size: $font-size-xs;
        color: $medium-gray;
        text-align: center;
        font-family: $font-family;
        @include text-ellipsis;
      }
    }
  }
}

/* 打卡心得展示 */
.comment-section {
  margin: $spacing-md;
  padding: $spacing-2xl;
  border-radius: $border-radius-xl;
  @include glass-effect;
  border: 2px solid $border-color-light;
  box-shadow: $shadow-lg;

  .comment-content {
    .comment-text {
      font-size: $font-size-base;
      line-height: $line-height-relaxed;
      color: $dark-gray;
      font-family: $font-family;
      display: block;
      word-wrap: break-word;
      white-space: pre-wrap;
    }
  }
}

/* 分享按钮区域 */
.share-section {
  padding: 0 $spacing-2xl;
  margin-top: $spacing-2xl;
  display: flex;
  flex-direction: column;
  gap: $spacing-md;

  .share-btn {
    width: 100%;
    height: 56px;
    background: $blue-gradient;
    border-radius: $border-radius-3xl;
    border: none;
    @include center-flex;
    gap: $spacing-sm;
    transition: $transition-all;
    box-shadow: $shadow-blue-lg;
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, $white-20, transparent);
      transition: left 0.5s ease;
    }

    &:active:not(.loading) {
      transform: scale(0.98);
      box-shadow: $shadow-blue-lg;

      &::before {
        left: 100%;
      }
    }

    &.loading {
      background: linear-gradient(135deg, #a8a8a8 0%, #888888 100%);
      box-shadow: 0 4px 16px rgba(168, 168, 168, 0.3);

      &::after {
        content: '';
        position: absolute;
        width: 20px;
        height: 20px;
        border: 2px solid $white-30;
        border-top: 2px solid $white;
        border-radius: $border-radius-full;
        animation: spin 1s linear infinite;
        margin-right: $spacing-sm;
      }
    }

    .share-icon {
      font-size: $font-size-lg;
    }

    .btn-text {
      font-size: $font-size-lg;
      font-weight: $font-weight-semibold;
      color: $white;
      font-family: $font-family;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }
  }

  .explore-btn {
    width: 100%;
    height: 56px;
    background: $green-gradient;
    border-radius: $border-radius-3xl;
    border: none;
    @include center-flex;
    gap: $spacing-sm;
    transition: $transition-all;
    box-shadow: 0 4px 16px rgba(50, 205, 50, 0.3);
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: -100%;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, $white-20, transparent);
      transition: left 0.5s ease;
    }

    &:active {
      transform: scale(0.98);
      box-shadow: 0 4px 16px rgba(50, 205, 50, 0.4);

      &::before {
        left: 100%;
      }
    }

    .btn-text {
      font-size: $font-size-lg;
      font-weight: $font-weight-semibold;
      color: $white;
      font-family: $font-family;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }
  }

  .back-btn {
    width: 100%;
    height: 48px;
    background: $white-80;
    border-radius: $border-radius-3xl;
    border: 2px solid $border-color-light;
    @include center-flex;
    transition: $transition-all;
    box-shadow: $shadow-sm;

    &:active {
      transform: scale(0.98);
      background: $white-70;
    }

    .btn-text {
      font-size: $font-size-base;
      font-weight: $font-weight-medium;
      color: $dark-gray;
      font-family: $font-family;
    }
  }
}

/* 动画效果 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

@keyframes success-pulse {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.3;
  }
  50% {
    transform: translate(-50%, -50%) scale(1.1);
    opacity: 0.2;
  }
  100% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.3;
  }
}

/* 响应式适配 */
@media (max-width: 375px) {
  .books-section .books-grid .book-item {
    width: calc(50% - #{calc($spacing-lg / 2)});
  }
}

@media (max-height: 700px) {
  .success-banner {
    padding: $spacing-2xl $spacing-lg;
  }

  .reading-summary,
  .books-section,
  .comment-section {
    // margin: $spacing-sm;
    padding: $spacing-lg;
  }
}
</style>
